<?php
namespace ZL;

class SmartSDK
{
  public $appKey;
  public $appSecret;

  public function __construct($appkey = "",$appSecret = "")
  {
    $this->appKey = $appkey;
    $this->appSecret = $appSecret;
  }

  public function checkSign($sign,$params)
  {
    $params['appKey'] = $this->appKey;
    ksort($params);
    $stringToBeSigned = $this->appSecret;
		foreach ($params as $k => $v)
		{
			if("@" != substr($v, 0, 1))
			{
				$stringToBeSigned .= "$k$v";
			}
		}
		unset($k, $v);
		$stringToBeSigned .= $this->appSecret;

		$result = strtoupper(md5($stringToBeSigned));
    //echo $stringToBeSigned;
    if($result == $sign)
      return true;
    else
      return false;
  }

  protected function generateSign($params)
  {
    ksort($params);
    $stringToBeSigned = $this->appSecret;
		foreach ($params as $k => $v)
		{
			if("@" != substr($v, 0, 1))
			{
				$stringToBeSigned .= "$k$v";
			}
		}
		unset($k, $v);
		$stringToBeSigned .= $this->appSecret;
    //echo $stringToBeSigned;
		return strtoupper(md5($stringToBeSigned));
  }

  public function execute($requestUrl,$params)
  {
    $requestUrl .= "&";
    $sysParams["appKey"] = $this->appKey;
		$sysParams["timestamp"] = time();
    $sysParams["sign"] = $this->generateSign(array_merge($params, $sysParams));

    foreach ($sysParams as $sysParamKey => $sysParamValue)
		{
			$requestUrl .= "$sysParamKey=" . urlencode($sysParamValue) . "&";
		}
    $requestUrl = substr($requestUrl, 0, -1);

    return $this->curlPost($requestUrl,'POST',$params);
  }

  private function curlPost($url, $method = 'post', $data = '')
	{
		$ch = curl_init();
		$header = 'Accept-Charset: utf-8';
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		//curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$temp = curl_exec($ch);
		return $temp;
	}
}

?>